package com.kotlin.hxh.ui.fragment.first.child

import android.os.Build
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.transition.Fade
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.kotlin.hxh.R
import com.kotlin.hxh.adapter.FirstHomeAdapter
import com.kotlin.hxh.adapter.RecyclerViewHolder
import com.kotlin.hxh.base.BaseMainFragment
import com.kotlin.hxh.entity.Article
import com.kotlin.hxh.event.TabSelectedEvent
import com.kotlin.hxh.helper.DetailTransition
import com.kotlin.hxh.listener.OnItemClickListener
import com.kotlin.hxh.ui.activity.HxhActivity
import kotlinx.android.synthetic.main.zhihu_fragment_first_home.*
import kotlinx.android.synthetic.main.zhihu_fragment_fourth.*
import me.yokeyword.eventbusactivityscope.EventBusActivityScope

import org.greenrobot.eventbus.Subscribe

/**
 * @author huxh
 * @date 2018/12/15.
 */
class FirstHomeFragment : BaseMainFragment(), OnItemClickListener {
    val mAdpter by lazy {
        FirstHomeAdapter()
    }

    companion object {
        @JvmStatic
        fun newInstance(): FirstHomeFragment {
            val fragment = FirstHomeFragment()
            fragment.arguments = Bundle()
            return fragment
        }
    }

    var mScrollTotal: Int = 0
    var mInAtTop: Boolean = true
    val mTitles = arrayOf("Use imagery to express a distinctive voice and exemplify creative excellence.", "An image that tells a story is infinitely more interesting and informative.", "The most powerful iconic images consist of a few meaningful elements, with minimal distractions.", "Properly contextualized concepts convey your message and brand more effectively.", "Have an iconic point of focus in your imagery. Focus ranges from a single entity to an overarching composition.")

    val mImgRes = intArrayOf(R.drawable.bg_first, R.drawable.bg_second, R.drawable.bg_third, R.drawable.bg_fourth, R.drawable.bg_fifth)

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.zhihu_fragment_first_home, container, false)
        EventBusActivityScope.getDefault(_mActivity).register(this)
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    private fun initView() {
        toolbar.setTitle(R.string.home)
        refresh_layout.setColorSchemeResources(R.color.colorPrimary)
        refresh_layout.setOnRefreshListener(this::onRefresh)
        val manager = androidx.recyclerview.widget.LinearLayoutManager(_mActivity)
        recy.layoutManager = manager
        recy.adapter = mAdpter
        mAdpter.setOnItemClickListener(this)
        val articleList = mutableListOf<Article>()
        for (i in 0..8) {
            val index = i % 5
            articleList.add(Article(mTitles[index], mImgRes[index]))
        }
        mAdpter.setDatas(articleList)
        recy.addOnScrollListener(object : androidx.recyclerview.widget.RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: androidx.recyclerview.widget.RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                mScrollTotal += dy
                mInAtTop = mScrollTotal <= 0
                if (dy > 5) {
                    fab.hide()
                } else if (dy < -5) {
                    fab.show()
                }
            }
        })
        fab.setOnClickListener {
            Toast.makeText(_mActivity, "Action", Toast.LENGTH_LONG).show()
        }
    }

    fun onRefresh() {
        refresh_layout.postDelayed(object : Runnable {
            override fun run() {
                mAdpter.notifyDataSetChanged()
                refresh_layout.isRefreshing = false
            }
        }, 2000)
    }

    override fun onItemClick(positino: Int, view: View?, holder: androidx.recyclerview.widget.RecyclerView.ViewHolder) {
        if (positino == -1) return
        val fragment = FirstDetailFragment.newInstance(mAdpter.getItem(positino))
        // 这里是使用SharedElement的用例
        // LOLLIPOP(5.0)系统的 SharedElement支持有 系统BUG， 这里判断大于 > LOLLIPOP
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            exitTransition = Fade()
            fragment.enterTransition = Fade()
            fragment.sharedElementEnterTransition = DetailTransition()
            fragment.sharedElementReturnTransition = DetailTransition()
            // 25.1.0以下的support包,Material过渡动画只有在进栈时有,返回时没有;
            // 25.1.0+的support包，SharedElement正常
            if (holder is RecyclerViewHolder) {
                extraTransaction().addSharedElement(holder.getView(R.id.img), getString(R.string.image_transition))
                        .addSharedElement(holder.getView(R.id.tv_title), "tv")
                        .start(fragment)
            }
        } else {
            start(fragment)
        }

    }

    @Subscribe
    fun onTabSelectedEvent(event: TabSelectedEvent) {
        if (event.position != HxhActivity.FIRST) return
        if (mInAtTop) {
            refresh_layout.isRefreshing = true
            onRefresh()
        } else {
            scrollToTop()
        }
    }

    private fun scrollToTop() {
        recy.smoothScrollToPosition(0)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBusActivityScope.getDefault(_mActivity).unregister(this)
    }

}